package com.gable.report.common.filter;

import com.alibaba.fastjson.JSON;
import com.gable.report.common.util.ReturnResultUtil;
import com.gable.report.dao.IUserDao;
import com.gable.report.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权过滤器
 * @author jacky
 *
 */
@Component("authorizationFilter")
public class AuthorizationFilter implements Filter{
	
	@Autowired
	IUserDao userDao;

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		ReturnResultUtil rru = new ReturnResultUtil();
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String path = httpServletRequest.getServletPath();
        if(path.indexOf("user/login") > -1 || path.indexOf("user/sendCode") > -1 || path.indexOf("user/checkCode") > -1 || path.indexOf("user/updatePasswordByPhone") > -1 || path.indexOf("server/list") > -1){
        	chain.doFilter(httpServletRequest, httpServletResponse);
        	return;
        }
        if(request.getParameter("userId")==null || request.getParameter("userId").equals("")){
			rru.setRet(-1);
			rru.setMsg("用户id不能为空！");
			httpServletResponse.getWriter().println(JSON.toJSONString(rru));
			return;
		}
		if(request.getParameter("secretKey")==null || request.getParameter("secretKey").equals("")){
			rru.setRet(-1);
			rru.setMsg("授权码不能为空！");
			httpServletResponse.getWriter().println(JSON.toJSONString(rru));
			return;
		}
		Long userId = Long.parseLong(request.getParameter("userId"));
		String secretKey = httpServletRequest.getParameter("secretKey");
		User user = userDao.queryUserById(userId);
		if(user == null){
			rru.setRet(-1);
			rru.setMsg("用户信息不存在！");
			httpServletResponse.getWriter().println(JSON.toJSONString(rru));
			return;
		}
		if(user.getSecretKey() == null || user.getSecretKey().equals("")){
			rru.setRet(-1);
			rru.setMsg("当前用户授权码不存在，请重新登录");
			httpServletResponse.getWriter().println(JSON.toJSONString(rru));
			return;
		}
		if(!user.getSecretKey().equals(secretKey)){
			rru.setRet(-1);
			rru.setMsg("授权码错误");
			httpServletResponse.getWriter().println(JSON.toJSONString(rru));
			return;
		}
		chain.doFilter(httpServletRequest, httpServletResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
